# 你写了很多仅仅用作数据结构的类，不想写太多烦人的 __init__() 函数。
# 可以在一个基类中写一个公用的 __init__() 函数。


import math
class Structure1:
    _fileds = []

    def __init__(self, *args):
        if len(args) != len(self._files):
            raise TypeError('Expected {} arguments'.format(len(self._fileds)))
        for name, value in zip(_fileds, args):
            setattr(self, name, value)


class Stockl(Structure1):
    _fileds = ['name', 'shares', 'price']


class Point(Structure1):
    _fileds = ['x', 'y']


class Circle(Structure1):
    _fileds = ['radius']

    def area(self):
        return math.pi * radius ** 2


s = Stock('ACME', 50, 91.1)
p = Point(2, 3)
c = Circle(4.5)
s2 = Stock('ACME', 50)

try:
    s2 = Stock('ACME', 50)
except Exception as e:
    print(e)


# 支持关键字参数
class Structure2:
    _fields = []
    def __init__(self, *args, **kwargs):
        if len(args) > len(self._fields):
            raise TypeError('Expected {} arguments'.format(len(self._fileds)))

        for name, value in zip(self._fileds, args):
            setattr(self, name, value)

        for name in self._fileds[len(args):]:
            setattr(self, name, kwargs.pop(name))

        if kwargs:
            raise TypeError('Invalid argument(s): {}'.format(','.join(kwargs)))


# 将不在_fields 中的名称加入到属性中
class Structure3:
    _fields = []
    def __init__(self, *args, **kwargs):
        if len(args) != len(self._fields):
            raise TypeError('Expected {} arguments'.format(len(self._fileds)))

        for name, value in zip(self._fields, args):
            setattr(self, name, value)

        extra_args = kwargs.keys() - self._fields
        for name in extra_args:
            setattr(self, name, kwargs.pop(name))

        if kwargs:
            raise TypeError('Duplicate values for {}'.format(','.join(kwargs)))
